package cn.csq.rpc.transport;

import cn.csq.rpc.Peer;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author csq
 * @version 1.0.0
 * @ClassName HTTPTransportClient.java
 * @Description 客户端连接实现类
 * @createTime 2021年12月19日 23:47:00
 */
public class HTTPTransportClient implements TransportClient{

    private String url;
    @Override
    public void connect(Peer peer) {
        //拼接httpurl
        this.url = "http://" + peer.getHost() + ":" + peer.getPort();
    }

    @Override
    public InputStream write(InputStream data) throws IOException {
        //写入数据 打开connect 使用HttpURLConnection做实现
        try {
            HttpURLConnection httpConn = (HttpURLConnection) new URL(url).openConnection();
            //需要读数据和写入数据 设置in/out为true
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            //关闭缓存
            httpConn.setUseCaches(false);
            //设置连接方法为post 开启连接
            httpConn.setRequestMethod("POST");
            httpConn.connect();
            //将数据copy到http连接的out
            IOUtils.copy(data, httpConn.getOutputStream());

            int responseCode = httpConn.getResponseCode();
            if (HttpURLConnection.HTTP_OK == responseCode) {
                return httpConn.getInputStream();
            } else {
                return httpConn.getErrorStream();
            }
        } catch (IOException e) {
            throw new IOException();
        }
    }

    @Override
    public void close() {
        //http是短连接的 没必要去close
    }
}
